﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;

namespace Slex.Lib.Interactions
{
    /// <summary>
    /// Utility methods for visiting the visual tree
    /// </summary>
    public static class VisualTreeUtils
    {
        public static FrameworkElement FindElement(string name, DependencyObject reference)
        {
            return FindName<FrameworkElement>(name, reference);
        }

        public static T FindName<T>(string name, DependencyObject reference) where T : FrameworkElement
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            if (reference == null)
            {
                throw new ArgumentNullException("reference");
            }

            return FindElementInternal<T>(name, reference);
        }

        private static T FindElementInternal<T>(string name, DependencyObject reference) where T : FrameworkElement
        {
            foreach (DependencyObject obj in GetChildren(reference))
            {
                T elem = obj as T;
                if (elem != null && elem.Name == name)
                {
                    return elem;
                }

                elem = FindElementInternal<T>(name, obj);
                if (elem != null)
                {
                    return elem;
                }
            }

            return null;
        }

        private static IEnumerable<DependencyObject> GetChildren(DependencyObject reference)
        {
            int childCount = VisualTreeHelper.GetChildrenCount(reference);
            for (int i = 0; i < childCount; i++)
            {
                yield return VisualTreeHelper.GetChild(reference, i);
            }
        }
    }
}
